<?php
namespace app\task\controller;

use \think\Controller;
use \think\Db;
use \think\Log;
use \think\Session;
use \think\Config;
use wxopen\WxComponentService;

/****
	计划任务控制器
***/

class Task extends Controller
{
	/***
	渠道结算记录自动生成
	***/
	public function balance() {
		$member = db('member')->alias('m')->join('cps_member_extend e','e.uid = m.uid')->where(array('m.status'=>1,'m.group'=>3,'m.is_top'=>1))->field('m.uid,e.percentage')->select();
		
		foreach($member as $k=>$v){
			
			$startdata = mktime(0,0,0,date('m'),date('d'),date('Y'));
			$enddata = mktime(23,59,59,date('m'),date('d'),date('Y'));

			$wxmp = db('wxmp')->where(['status'=>1,'uid'=>$v['uid']])->column('id,appid');
			//渠道存在服务号的情况下
			if($wxmp){
				foreach ($wxmp as $kk=>$vv){
					$data = array();
					$order = db('order')->where(array('agentid'=>$v['uid'],'is_kouliang'=>0,'status'=>1,'wxmpid'=>$kk,'create_time' => array(array('gt',$startdata),array('lt',$enddata))))->field('count(id) as num,SUM(money) as money')->find();
					//充值金额
					if($order['money'] >0){			
						//未结算
						$pay_balance = db('pay_balance')->where(array('uid'=>$v['uid'],'type'=>1,'status' =>0,'wxmpid'=>$kk,'create_time' => strtotime(date('Y-m-d'))))->find();
						//帐单金额
						$balmoney = $order['money']*$v['percentage'];
						if($pay_balance){
								
							$data = array(
								'update_time' => time(),
								'num'=>$order['num'],
								'money'=>$order['money'],
								'balmoney'=>$balmoney,
							);
							db('pay_balance')->where('id',$pay_balance['id'])->update($data);
						}else{
							$data = array(
								'uid'=>$v['uid'],
								'wxmpid'=>$kk,
								'type'=>1,   //1:自己推广收益 2:代理盈利差价
								'create_time' => strtotime(date('Y-m-d')),
								'update_time' => time(),
								'num'=>$order['num'],
								'money'=>$order['money'],
								'balmoney'=>$balmoney,
								'percentage'=>$v['percentage'],
							);
							db('pay_balance')->insert($data);
						}
					}
				}
			}else{
				$data = array();

				$order = db('order')->where(array('agentid'=>$v['uid'],'is_kouliang'=>0,'status'=>1,'create_time' => array(array('gt',$startdata),array('lt',$enddata))))->field('count(id) as num,SUM(money) as money')->find();

				//充值金额
				if($order['money'] >0){			
					//未结算
					$pay_balance = db('pay_balance')->where(array('uid'=>$v['uid'],'type'=>1,'status' =>0,'create_time' => strtotime(date('Y-m-d'))))->find();
					//帐单金额
					$balmoney = $order['money']*$v['percentage'];
					if($pay_balance){
							
						$data = array(
							'update_time' => time(),
							'num'=>$order['num'],
							'money'=>$order['money'],
							'balmoney'=>$balmoney,
						);
						db('pay_balance')->where('id',$pay_balance['id'])->update($data);
					}else{
						$data = array(
							'uid'=>$v['uid'],
							'type'=>1,   //1:自己推广收益 2:代理盈利差价
							'create_time' => strtotime(date('Y-m-d')),
							'update_time' => time(),
							'num'=>$order['num'],
							'money'=>$order['money'],
							'balmoney'=>$balmoney,
							'percentage'=>$v['percentage'],
						);
						db('pay_balance')->insert($data);
					}
				}
			}
			
		}
	}

	/***
	代理结算记录自动生成
	***/
	public function dailibalance() {
		$smember = db('member')->alias('m')->join('cps_member_extend e','e.uid = m.uid')->where(array('m.status'=>1,'m.group'=>4))->field('m.uid,m.s_uid as topuid,e.percentage')->select();
		
		$member = [];
		foreach ($smember as $k=>$v){
			$member[$k] = $v;
			$member[$k]['toppercentage'] = db('member')->alias('m')->join('cps_member_extend e','e.uid =m.uid')->where(array('m.status'=>1,'m.uid'=>$v['topuid']))->value('e.percentage');
		}
		
		foreach($member as $k=>$v){
			
			$startdata = mktime(0,0,0,date('m'),date('d'),date('Y'));
			
			$enddata = mktime(23,59,59,date('m'),date('d'),date('Y'));

			$wxmp = db('wxmp')->where(['status'=>1,'uid'=>$v['topuid']])->column('id,appid');
			//渠道存在服务号的情况下
			if($wxmp){
				foreach ($wxmp as $kk=>$vv){
					$data = array();

					$order = db('order')->where(array('agentid'=>$v['uid'],'is_kouliang'=>0,'status'=>1,'wxmpid'=>$kk,'create_time' => array(array('gt',$startdata),array('lt',$enddata))))->field('count(id) as num,SUM(money) as money')->find();
					//充值金额大于0 生成结算单
					if($order['money'] >0){			
						//自己推广收益是否已经结算
						$pay_balance = db('pay_balance')->where(array('uid'=>$v['uid'],'type'=>1,'status' =>0,'wxmpid'=>$kk,'create_time' => strtotime(date('Y-m-d'))))->find();
						if($pay_balance){
							$data = array(
								'update_time' => time(),
								'num'=>$order['num'],
								'money'=>$order['money'],
								'balmoney'=>$order['money']*$v['percentage'],
							);
							db('pay_balance')->where('id',$pay_balance['id'])->update($data);
						}else{
							$data = array(
								'uid'=>$v['uid'],
								'wxmpid'=>$kk,
								'create_time' => strtotime(date('Y-m-d')),
								'create_time' => strtotime(date('Y-m-d')),
								'update_time' => time(),
								'num'=>$order['num'],
								'money'=>$order['money'],
								'balmoney'=>$order['money']*$v['percentage'],
								'percentage'=>$v['percentage'],
							);
							db('pay_balance')->insert($data);
						}

						//渠道盈利差价是否已经结算
						$toppay_balance = db('pay_balance')->where(array('uid'=>$v['topuid'],'type'=>2,'status' =>0,'wxmpid'=>$kk,'create_time' => strtotime(date('Y-m-d'))))->find();
						if($toppay_balance){
							$topdata = array(
								'update_time' => time(),
								'num'=>$order['num'],
								'money'=>$order['money'],
								'balmoney'=>$order['money']*($v['toppercentage']-$v['percentage']),
							);
							db('pay_balance')->where('id',$toppay_balance['id'])->update($topdata);
						}else{
							$topdata = array(
								'uid'=>$v['topuid'],
								'wxmpid'=>$kk,
								'type'=>2,   //1:自己推广收益 2:盈利差价
								'create_time' => strtotime(date('Y-m-d')),
								'create_time' => strtotime(date('Y-m-d')),
								'update_time' => time(),
								'num'=>$order['num'],
								'money'=>$order['money'],
								'balmoney'=>$order['money']*($v['toppercentage']-$v['percentage']),
								'percentage'=>$v['toppercentage']-$v['percentage'],
							); 
							db('pay_balance')->insert($topdata);
						}
					}
				}

			}else{
				$data = array();

				$order = db('order')->where(array('agentid'=>$v['uid'],'is_kouliang'=>0,'status'=>1,'create_time' => array(array('gt',$startdata),array('lt',$enddata))))->field('count(id) as num,SUM(money) as money')->find();

				//充值金额大于0 生成结算单
				if($order['money'] >0){			
					//自己推广收益是否已经结算
					$pay_balance = db('pay_balance')->where(array('uid'=>$v['uid'],'type'=>1,'status' =>0,'create_time' => strtotime(date('Y-m-d'))))->find();
					if($pay_balance){
						$data = array(
							'update_time' => time(),
							'num'=>$order['num'],
							'money'=>$order['money'],
							'balmoney'=>$order['money']*$v['percentage'],
						);
						db('pay_balance')->where('id',$pay_balance['id'])->update($data);
					}else{
						$data = array(
							'uid'=>$v['uid'],
							'create_time' => strtotime(date('Y-m-d')),
							'create_time' => strtotime(date('Y-m-d')),
							'update_time' => time(),
							'num'=>$order['num'],
							'money'=>$order['money'],
							'balmoney'=>$order['money']*$v['percentage'],
							'percentage'=>$v['percentage'],
						);
						db('pay_balance')->insert($data);
					}

					//渠道盈利差价是否已经结算
					$toppay_balance = db('pay_balance')->where(array('uid'=>$v['topuid'],'type'=>2,'status' =>0,'create_time' => strtotime(date('Y-m-d'))))->find();
					if($toppay_balance){
						$topdata = array(
							'update_time' => time(),
							'num'=>$order['num'],
							'money'=>$order['money'],
							'balmoney'=>$order['money']*($v['toppercentage']-$v['percentage']),
						);
						db('pay_balance')->where('id',$toppay_balance['id'])->update($topdata);
					}else{
						$topdata = array(
							'uid'=>$v['topuid'],
							'type'=>2,   //1:自己推广收益 2:盈利差价
							'create_time' => strtotime(date('Y-m-d')),
							'create_time' => strtotime(date('Y-m-d')),
							'update_time' => time(),
							'num'=>$order['num'],
							'money'=>$order['money'],
							'balmoney'=>$order['money']*($v['toppercentage']-$v['percentage']),
							'percentage'=>$v['toppercentage']-$v['percentage'],
						); 
						db('pay_balance')->insert($topdata);
					}
				}
			}
		}
	}
	
	/*******模板消息自动发送******/
	public function send_templatemsg() {
		$template = db('TemplateMsg')->where(array('status'=>1,'completed'=>0,'scheduled_at'=>array('<=',time())))->select();
		
		if($template){
			foreach($template as $k=>$v){
					if($v['wxmpid']){
						$wxmpid = $v['wxmpid'];
						//获取推送用户
						$appid= db('wxmp')->where(['id'=>$v['wxmpid'],'status'=>1])->value('appid');
					}else{
						$wxmpid = 0;
						//获取推送用户
						$appid= db('wxmp')->where('uid='.$v['uid'])->value('appid');
					}

					if($v["andience"]==2){
						
						//$appid = db('wxmp')->where('id',$v['wxmpid'])->value('appid');
						
						$map['f.appid']=$appid;

						if($v["gender"]>0){
							$map['f.sex']=$v["gender"];
						}
						if($v["paid"]>0){
							$map['m.pay']=array(">",0);
						}
						if($v["welth"]>0){
							switch($v["welth"]){
								case '500':
									$map['m.egold']=array("<=",500);
									break;
								case '2000':
									$map['m.egold']=array(array(">",500),array("<=",2000));
									break;
								case '5000':
									$map['m.egold']=array(array(">=",2000),array("<=",5000));
									break;
							}
						}

						if($v["subscribe_time"]>0){
							$subscribe_time = strtotime(date('Y-m-d'))+($v["subscribe_time"]*3600*7);
							$map['f.subscribe_time']=array("<=",$subscribe_time);
						}
						
						$member = db('wechat_fans')->alias('f')->join(' cps_member_userapi u','u.wxmpid = f.openid','LEFT')->join(' cps_member m','m.uid = u.uid','LEFT')->where($map)->column('u.uid,f.openid');
					
					}else{
						//$appid = db('wxmp')->where('id',$v['wxmpid'])->value('appid');
						$member = db('MemberUserapi')->where('appid',$appid)->column('wxmpid','uid');
					}
					
					$auto = db('wxmp')->where('appid',$appid)->field('appid,autoconfig,open_appid')->find();
					//公众号自动配置
					if($auto["autoconfig"]){
						$account = db('wxopen_account')->where('appid',$auto['open_appid'])->find();
						$wxComponentConfig = array(
							'component_appid'=>$account["appid"],
							'component_appsecret'=>$account["appsecret"],
							'encodingAesKey'=>$account["encodingKey"],
							'token'=>$account["token"]
						);
					}
					
					if($auto["autoconfig"]){
						$wxAuth = new WxComponentService($wxComponentConfig);
						$message = $wxAuth->getWechat($auto['appid']);
					}else{
						$message = &load_wechat($v['uid'],'Message');
					}
					
					
					foreach($member as $kk=>$vv){
						$data = str_replace(array("{nickname}","{time}","{coinnum}"),array(get_nickname($kk),date('Y-m-d H:i:s'),get_egold($kk)),$v["template_value"]);
						$template=[
							"touser"=>$vv,
							"template_id"=>$v["template_id"],
							"url"=>$v["url"],
							"data"=>json_decode($data,true)
						];
						$message->sendTemplateMessage($template);
					}
				db('TemplateMsg')->where("id=".$v['id'])->setField('completed', 1);
			}
		}
		
	}

    /**
      * send_intelligent [智能推送]
      *
      * @return type
    **/
	public function send_intelligent(){
		
		if(date('H')>=7&&date('H')<=23){
			$intelligent = db('wechat_intelligent')->where("open=1 and type in (1,2,5,6,7,8)")->select();
			//$intelligent = db('wechat_intelligent')->where("open=1 and type in (1) and uid = 12 and wxmpid = 5")->select();
			
			$intelligent_config = \think\Config::get('intelligent');
			if($intelligent){
				foreach ($intelligent as $k=>$v){
					
					$Intelligent_model = model('Intelligent');
					if($v['wxmpid']){
						$wxmpid = $v['wxmpid'];
						//获取推送用户
						$appid= db('wxmp')->where(['id'=>$v['wxmpid'],'status'=>1])->value('appid');
					}else{
						$wxmpid = 0;
						//获取推送用户
						$appid= db('wxmp')->where('uid='.$v['uid'])->value('appid');
					}

					if(empty($appid)){
						continue;
					}
					
					$fans = [];
					if($v['type']==1 || $v['type']==2){

						$pushtime = json_decode($v["pushtime"],true);
						$intervaltime = [];
							
						if($pushtime){
							foreach ($pushtime as $pv){
								$intervaltime[] =$pv["hour"].$pv["minute"];
							}
						}
						
						if(in_array(date("Hi"),$intervaltime)){
							$fans = db('wechat_fans')->alias('f')->join('cps_member_userapi u','u.wxmpid= f.openid')->where(array('f.appid'=>$appid,'subscribe'=>1))->where('f.update_at','between time',[time()-48*3600,time()])->column('u.uid,f.openid,f.update_at');
						}
						
						//$fans = db('wechat_fans')->alias('f')->join('cps_member_userapi u','u.wxmpid= f.openid')->where(array('f.appid'=>$appid,'subscribe'=>1))->where('f.update_at','between time',[time()-48*3600,time()-$intelligent_config[$v["type"]]['interval']])->column('u.uid,f.openid,f.update_at');
					}elseif($v['type']==5){
						//$fans = db('order')->alias('o')->join('cps_member_userapi u','u.uid= o.uid')->join('wechat_fans f','u.wxmpid= f.openid')->where('o.update_time','between time',[time()-48*3600,time()-$intelligent_config[$v["type"]]['interval']])->where(["o.status"=>0])->column('u.uid,f.openid,f.update_at,o.create_time');
						$fans = db('order')->where("status",0)->where('create_time','between time',[time()-24*60*60-60,time()-24*60*60])->field('uid,openid,create_time')->column('uid,openid,create_time');
					}elseif($v['type']==6){//关注图文推送
						$pushtime = json_decode($v["pushtime"],true);
						$intervaltime = [];
							
						if($pushtime){
							foreach ($pushtime as $pv){
								$intervaltime[] =$pv["hour"].$pv["minute"];
							}
						}
						
						if(in_array(date("Hi"),$intervaltime)){
							$fans = db('wechat_fans')->alias('f')->join('cps_member_userapi u','u.wxmpid= f.openid')->where(array('f.appid'=>$appid,'subscribe'=>1))->where('f.subscribe','between time',[time()-600,time()])->column('u.uid,f.openid,f.update_at');
						}
						//$fans = db('wechat_fans')->alias('f')->join('cps_member_userapi u','u.wxmpid= f.openid')->where(array('f.appid'=>$appid,'subscribe'=>1))->where('f.subscribe','between time',[time()-$intelligent_config[$v["type"]]['interval']-600,time()-$intelligent_config[$v["type"]]['interval']])->column('u.uid,f.openid,f.update_at');
						
					}elseif($v['type']==7){//签到图文推送
						$pushtime = json_decode($v["pushtime"],true);
						$intervaltime = [];
							
						if($pushtime){
							foreach ($pushtime as $pv){
								$intervaltime[] =$pv["hour"].$pv["minute"];
							}
						}
						
						if(in_array(date("Hi"),$intervaltime)){
							$fans = db('qiandao')->alias('q')->join('cps_member_userapi u','u.uid= q.uid')->join('wechat_fans f','u.wxmpid= f.openid')->where('q.qiandao_time','between time',[time()-48*3600,time()])->column('u.uid,f.openid,f.update_at');

						}
						//$fans = db('qiandao')->alias('q')->join('cps_member_userapi u','u.uid= q.uid')->join('wechat_fans f','u.wxmpid= f.openid')->where('q.qiandao_time','between time',[time()-48*3600,time()-$intelligent_config[$v["type"]]['interval']])->column('u.uid,f.openid,f.update_at');
					}elseif($v['type']==8){
						
						if($v["pushtype"]==1){//下单后30分钟内未支付
							$fans = db('order')->alias('o')->join('cps_member m','m.uid= o.uid')->join('cps_member_userapi u','u.uid= o.uid')->join('wechat_fans f','u.wxmpid= f.openid')->where('o.create_time','between time',[time()-1800,time()-1860])->where(["o.status"=>0,"m.pay"=>0])->column('u.uid,f.openid,f.update_at');
						}elseif($v["pushtype"]==2){//用户关注后第12小时
							$fans = db('order')->alias('o')->join('cps_member m','m.uid= o.uid')->join('cps_member_userapi u','u.uid= o.uid')->join('wechat_fans f','u.wxmpid= f.openid')->where('f.subscribe_time','between time',[time()-12*3600-60,time()-12*3600])->where(["o.status"=>0,"m.pay"=>0])->column('u.uid,f.openid,f.update_at');
						}elseif($v["pushtype"]==3){//用户关注后第24小时
							$fans = db('order')->alias('o')->join('cps_member m','m.uid= o.uid')->join('cps_member_userapi u','u.uid= o.uid')->join('wechat_fans f','u.wxmpid= f.openid')->where('f.subscribe_time','between time',[time()-24*3600-60,time()-24*3600])->where(["o.status"=>0,"m.pay"=>0])->column('u.uid,f.openid,f.update_at');
						}/*else{
							$fans = db('order')->alias('o')->join('cps_member m','m.uid= o.uid')->join('cps_member_userapi u','u.uid= o.uid')->join('wechat_fans f','u.wxmpid= f.openid')->where('o.update_time','between time',[time()-48*3600,time()-$intelligent_config[$v["type"]]['interval']])->where(["o.status"=>0,"m.pay"=>0])->column('u.uid,f.openid,f.update_at');
						}*/
					}
					//
					/*
					$fans = [
						596=>[
							"uid"=>596,
							"openid"=>"ouAmr6RLDQISTsUPQZcrAFHA-7V0",
							"create_time"=>1651043373
						]
					];*/
					//var_dump($fans);exit();
					//开始发送
					if($fans){
						foreach ($fans as $ko=>$vo){
									
							//获取模板内容
							$data = $Intelligent_model->articles($v["type"],$ko,$v['uid'],$appid,$wxmpid);							

							if($v['type']==5 || $v['type']==8){
								//$is_push = db('customservice_log')->where(['type'=>$v["type"],'openid'=>$vo['openid']])->where('create_at','between',[$starttime,$endtime])->find();
								/*
								$is_push = db('customservice_log')->where(['type'=>$v["type"],'openid'=>$vo['openid']])->find();
								
								//消息未发送的时候
								if(empty($is_push)){
									$re = $this->send_customservice($v['uid'],$appid,$vo['openid'],$data,"text");
									if($re){
										db('customservice_log')->insert(['type'=>$v["type"],'openid'=>$vo['openid'],'create_at'=>time()]);
									}
								}
								*/
								$this->send_customservice($v['uid'],$appid,$vo['openid'],$data,"text");
							}else{
								$this->send_customservice($v['uid'],$appid,$vo['openid'],$data);
							}
						}	
					}
				}
			}

		}
		exit();
	}
	
	//智能托管  每天推送一次
	public function intelligent_hosting() {
		if(date("Hi")==2000){
			$intelligent = db('wechat_intelligent')->where("open=1 and type =9")->select();
			//$intelligent = db('wechat_intelligent')->where("open=1 and type =9 and uid = 12 and wxmpid = 5")->select();
			
			$intelligent_config = \think\Config::get('intelligent');
			if($intelligent){
				foreach ($intelligent as $k=>$v){
					//1:为需要推送的
					if($intelligent_config[$v['type']]['push']==1){
						
						if($v['wxmpid']){
							$wxmpid = $v['wxmpid'];
							//获取推送用户
							$appid= db('wxmp')->where(['id'=>$v['wxmpid'],'status'=>1])->value('appid');
						}else{
							$wxmpid = 0;
							//获取推送用户
							$appid= db('wxmp')->where('uid='.$v['uid'])->value('appid');
						}
						
						$fans = db('wechat_fans')->alias('f')->join('cps_member_userapi u','u.wxmpid= f.openid')->where(array('f.appid'=>$appid,'subscribe'=>1))->where('f.update_at','between time',[time()-48*3600,time()])->column('u.uid,f.openid,f.update_at');
						
						
						$map = [];
						$map["status"] = 1;
						if($v["channel"]==2){//男频
							$map["channel"] = 1;
						}elseif($v["channel"]==3){//女频
							$map["channel"] = 2;
						}

						$site_url = get_menuurl($v["uid"],0,$appid);

						$list  = $this->random_data(1,"novel",$map,"id,title,cover,intro");
						
						$data = array();
						
						if($list){
							foreach ($list as $vo){
								$data["articles"][] = array(
									"title"=>$vo["title"],
									"description"=>$vo["intro"],
									"picurl"=>$site_url.$vo["cover"],
									"url"=>$site_url."/book/info/id/".$vo["id"],
								);
							}
						}
						
						if($fans){
							foreach ($fans as $ko=>$vs){
								//发送
								$this->send_customservice($v['uid'],$appid,$vs['openid'],$data);
							}	
						}
					}
				}
			}
		}
		exit();
	}

	//托管阅读记录推送

	public function intelligent_hosting_history() {
		
		$intelligent = db('wechat_intelligent')->where("open=1 and type =10")->select();
		
		$intelligent_config = \think\Config::get('intelligent');
		if($intelligent){
			foreach ($intelligent as $k=>$v){
				$pushtime = json_decode($v["pushtime"],true);
				
				$hour = [];
				$minute = []; 
				if($pushtime){
					foreach ($pushtime as $pv){
						$hour[] =$pv["hour"];
						$minute[] =$pv["minute"]; 
					}
				}

				if(in_array(date("H"),$hour)&&in_array(date("i"),$minute)){
					
					if($v['wxmpid']){
						$wxmpid = $v['wxmpid'];
						//获取推送用户
						$appid= db('wxmp')->where(['id'=>$v['wxmpid'],'status'=>1])->value('appid');
					}else{
						$wxmpid = 0;
						//获取推送用户
						$appid= db('wxmp')->where('uid='.$v['uid'])->value('appid');
					}
					
					$fans = db('wechat_fans')->alias('f')->join('cps_member_userapi u','u.wxmpid= f.openid')->where(array('f.appid'=>$appid,'subscribe'=>1))->where('f.update_at','between time',[time()-48*3600,time()])->column('u.uid,f.openid,f.update_at');

					$Intelligent_model = model('Intelligent');
					if($fans){
						foreach ($fans as $ko=>$vo){
							//获取模板内容
							$data = $Intelligent_model->articles(1,$ko,$v['uid'],$appid,$wxmpid);
							$data["articles"][0]["title"]="看小说不能看一半，精彩不断，继续阅读下一章！";
							$this->send_customservice($v['uid'],$appid,$vo['openid'],$data);
						}
					}
				}
			}
		}
		
	}
	
	//高级群发
	public function massmsg() {
		$massmsg = db('wxmp_massmsg')->where("status=1 and completed=0 and scheduled_at <=".time())->select();
		
		if($massmsg){
			foreach ($massmsg as $k=>$v){
					
				if($v['wxmpid']){
					$wxmpid = $v['wxmpid'];
					//获取推送用户
					$appid= db('wxmp')->where(['id'=>$v['wxmpid'],'status'=>1])->value('appid');
				}else{
					$wxmpid = 0;
					//获取推送用户
					$appid= db('wxmp')->where('uid='.$v['uid'])->value('appid');
				}
				
				if($v["andience"]==1){//所有用户
					$fans = db('wechat_fans')->alias('f')->join('cps_member_userapi u','u.wxmpid= f.openid')->where(array('f.appid'=>$appid,'subscribe'=>1))->column('f.openid');
				}elseif($v["andience"]==2){//条件用户
					$map = [];
					$map['f.appid'] = $appid;
					$map['f.subscribe'] = 1;
					if($v["gender"]){//性别
						$map['f.sex'] = $v["gender"];
					}
					if($v["paid"]>0){
						//充值情况
						if($v["paid"]==1){
							$map['m.pay']=array(">",0);
						}else{
							$map['m.pay']=0;
						}
					}
					//充值金额
					if($v["startegold"]>0 && $v["endegold"]>0){
						$map['o.money']=array(array(">=",$v["startegold"]),array("<=",$v["endegold"]));
					}
					//书币
					if($v["startwelth"]>0 && $v["endwelth"]>0){
						$map['m.egold']=array(array(">=",$v["startwelth"]),array("<=",$v["endwelth"]));
					}
					//群发次数
					if($v["startnum"]>0 && $v["endnum"]>0){
						$map['ml.num']=array(array(">=",$v["startnum"]),array("<=",$v["endnum"]));
					}
					$fans = db('wechat_fans')->alias('f')->join(' cps_member_userapi u','u.wxmpid = f.openid','LEFT')->join(' cps_member m','m.uid = u.uid','LEFT')->join(' cps_order o','m.uid = o.uid','LEFT')->join(' cps_wxmp_massmsg_log ml','f.openid = ml.openid','LEFT')->where($map)->column('f.openid');
				}elseif($v["andience"]==3){//条件用户
					$content_user = explode("\n",$v["content_user"]);
					if(is_array($content_user)){
						$map['m.uid'] = ['in',$content_user];
						$fans = db('wechat_fans')->alias('f')->join(' cps_member_userapi u','u.wxmpid = f.openid','LEFT')->join(' cps_member m','m.uid = u.uid','LEFT')->where($map)->column('f.openid');
					}else{
						$fans = [];
					}
				}
				
				if(!empty($fans)){
					if($v["type"]==1){
						$media_id = $this->getForever($wxmpid,$v["uid"]);
						$postdata = array(
							"touser"=>$fans,
							"msgtype"=>"mpnews",
							"mpnews" =>array ("media_id" =>$media_id),
							"send_ignore_reprint" =>$v["send_ignore_reprint"]
						);	
					}elseif($v["type"]==2){
						$postdata = array(
							"touser"=>$fans,
							"msgtype"=>"text",
							"text" =>array ("content" =>$v["editor"])
						);
					}
					
					$res = $this->sendMassMessage($appid,$postdata);
					
					if($res){
						foreach ($fans as $fv){
							$massfans = db('wxmp_massmsg_log')->where(["appid"=>$appid,"openid"=>$fv,"month"=>strtotime(date("Y-m"))])->find();
							if($massfans){
								db('wxmp_massmsg_log')->where("id=".$massfans['id'])->setInc('num');
							}else{
								db('wxmp_massmsg_log')->insert([
									'create_time'=>time(),
									'update_time'=>time(),
									'wxmpid'=>$wxmpid,
									'openid'=>$fv,
									'appid'=>$appid,
									'month'=>strtotime(date("Y-m")),
									'num'=>1
								]);
							}
						}
						db('wxmp_massmsg')->where("id=".$v['id'])->setField('completed', 1);
						
					}
				}
			}
		}
		exit();
	}
	
	//获取素材mediaid
	public function getForever($wxmpid,$uid) {
		
		if($wxmpid){
			$auto = db('wxmp')->where(['uid'=>$uid,'id'=>$wxmpid,'status'=>1])->field('appid,autoconfig,open_appid')->find();
			//公众号自动配置
			if(array_key_exists("autoconfig",$auto)){
				$account = db('wxopen_account')->where('appid',$auto['open_appid'])->find();
				$wxComponentConfig = array(
					'component_appid'=>$account["appid"],
					'component_appsecret'=>$account["appsecret"],
					'encodingAesKey'=>$account["encodingKey"],
					'token'=>$account["token"]
				);
				
				$wxAuth = new WxComponentService($wxComponentConfig);
				$wechat = $wxAuth->getWechat($auto["appid"]);
			}						
		}else{
			$wechat = load_wechat(1,'Media');
			
		}
		$media = $wechat->getForeverList('news', 0, 1);
		
		$media_id = 0;
		if(!empty($media["item"][0])){
			$media_id = $media["item"][0]["media_id"];
		}
		
		return $media_id;
	}

	//根据OpenID列表群发
	public function sendMassMessage($appid,$data){
		$auto = db('wxmp')->where('appid',$appid)->field('appid,autoconfig,open_appid')->find();
		

		//公众号自动配置
		if($auto["autoconfig"]){
			$account = db('wxopen_account')->where('appid',$auto['open_appid'])->find();
			$wxComponentConfig = array(
				'component_appid'=>$account["appid"],
				'component_appsecret'=>$account["appsecret"],
				'encodingAesKey'=>$account["encodingKey"],
				'token'=>$account["token"]
			);
			$wxAuth = new WxComponentService($wxComponentConfig);
			$wechat = $wxAuth->getWechat($auto["appid"]);
		}else{
			$wechat = load_wechat(1,'Message');
		}
		
		$result = $wechat->sendMassMessage($data);
				
		if($result["errcode"]==0){
			return true;
		}
		return false;
	}


	/****
		图文客服消息
		msgtype：1 客服消息  2:关注延迟消息
		type：1 客服消息	2:文本消息
	***/
	public function send_custom(){
		$intelligent = db('customservice')->where("type=1 and msgtype=1 and completed=0 and scheduled_at <=".time())->select();
		//$intelligent = db('customservice')->where("id=308")->select();
		if($intelligent){
			foreach ($intelligent as $k=>$v){
				$param = json_decode($v["param"],true);				
				
				//合并头条链接
				if($v["url"]&&$param["articles"]){
					foreach ($param["articles"] as $kk=>$vv){
						if($kk==0){
							$param["articles"][$kk]["url"] = $v["url"];
						}
					}
				}
				
				//获取推送用户
				if($v['wxmpid']){
					$wxmpid = $v['wxmpid'];
					//获取推送用户
					$appid= db('wxmp')->where(['id'=>$v['wxmpid'],'status'=>1])->value('appid');
				}else{
					$wxmpid = 0;
					//获取推送用户
					$appid= db('wxmp')->where('uid='.$v['uid'])->value('appid');
				}

				if(empty($appid)){
					continue;
				}
				/***
				if($v["andience"]==1){//付费用户
					$fans = db('wechat_fans')->alias('f')->join(' cps_member_userapi u','u.wxmpid = f.openid','LEFT')->join(' cps_member m','m.uid = u.uid','LEFT')->where(array('f.appid'=>$appid,'f.subscribe'=>1,'m.pay'=>array('>','0'),'f.update_at'=>array('>=',time()-48*3600)))->column('f.id,f.openid');

				}elseif($v["andience"]==3){//未付费用户
					$fans = db('wechat_fans')->alias('f')->join(' cps_member_userapi u','u.wxmpid = f.openid','LEFT')->join(' cps_member m','m.uid = u.uid','LEFT')->where(array('f.appid'=>$appid,'f.subscribe'=>1,'m.pay'=>0,'f.update_at'=>array('>=',time()-48*3600)))->column('f.id,f.openid');
				}else{
					$fans = db('wechat_fans')->where(array('appid'=>$appid,'subscribe'=>1,'update_at'=>array('>=',time()-48*3600)))->column('id,openid');
				}
				***/
				$map['f.appid']=$appid;
				$map['f.subscribe']=1;
				$map['f.update_at']=array('>=',time()-48*3600);
				//性别
				if($v["gender"]>0){
					$map['f.sex']=$v["gender"];
				}

				//充值情况
				if($v["paid"]==1){
					$map['m.pay']=array(">=",1);
				}elseif($v["paid"]==2){
					$map['m.pay']=0;
				}elseif($v["paid"]==3){
					$map['m.is_vip']=1;
				}elseif($v["paid"]==4){
					$map['m.pay']=1;
				}
				//剩余书币
				if($v["welth"]>0){
					switch($v["welth"]){
						case '1':
							$map['m.egold']=array("<=",100);
							break;
						case '2':
							$map['m.egold']=array("<=",500);
							break;
						case '3':
							$map['m.egold']=array("<=",2000);
							break;
						case '4':
							$map['m.egold']=array(">",2000);
							break;
					}
				}
				//关注时间
				if($v["subscribe_time"]>0){
					$subscribe_time = strtotime(date('Y-m-d'))+($v["subscribe_time"]*3600*24);
					$map['f.subscribe_time']=array("<=",$subscribe_time);
				}
				
				if($v["paid"]>0 || $v["welth"]>0){
					$fans = db('wechat_fans')->alias('f')->join(' cps_member_userapi u','u.wxmpid = f.openid','LEFT')->join(' cps_member m','m.uid = u.uid','LEFT')->where($map)->column('m.uid,f.openid');
				}else{
					$fans = db('wechat_fans')->alias('f')->join(' cps_member_userapi u','u.wxmpid = f.openid','LEFT')->join(' cps_member m','m.uid = u.uid','LEFT')->where($map)->column('m.uid,f.openid');
				}
				//var_dump($appid);exit();
				//开始推送
				if($fans){
					foreach ($fans as $vo){
						$is_push = db('customservice_log')->where(['msgid'=>$v['id'],'openid'=>$vo])->find();
						if(empty($is_push)){
							db('customservice_log')->insert(['msgid'=>$v['id'],'openid'=>$vo]);
							$this->send_customservice($v['uid'],$appid,$vo,$param);
						}
					}
				}
				db('customservice')->where("id=".$v['id'])->setField('completed', 1);
			}
		}

	}

	/*******
		文字客服消息自动发送
		msgtype：1 客服消息  2:关注延迟消息
		type：1 客服消息	2:文本消息
	******/
	public function send_textmsg() {
		$msg = db('customservice')->where("type = 2 and msgtype=1 and completed=0 and scheduled_at <=".time())->select();
		//$msg = db('customservice')->where("id=471")->select();
		var_dump($msg);exit();
		if($msg){
			foreach($msg as $k=>$v){
				$auto = array();
				var_dump($v);exit();
				if($v['wxmpid']){
					$appid = db('wxmp')->where('id',$v['wxmpid'])->value('appid');
				}else{
					$appid = db('wxmp')->where('uid',$v['uid'])->value('appid');
				}
					
				$map['f.appid']=$appid;
				$map['f.subscribe']=1;
				$map['f.update_at']=array('>=',time()-48*3600);
				//性别
				if($v["gender"]>0){
					$map['f.sex']=$v["gender"];
				}

				//充值情况
				if($v["paid"]==1){
					$map['m.pay']=array(">=",1);
				}elseif($v["paid"]==2){
					$map['m.pay']=0;
				}elseif($v["paid"]==3){
					$map['m.is_vip']=1;
				}elseif($v["paid"]==4){
					$map['m.pay']=1;
				}
				//剩余书币
				if($v["welth"]>0){
					switch($v["welth"]){
						case '1':
							$map['m.egold']=array("<=",100);
							break;
						case '2':
							$map['m.egold']=array("<=",500);
							break;
						case '3':
							$map['m.egold']=array("<=",2000);
							break;
						case '4':
							$map['m.egold']=array(">",2000);
							break;
					}
				}
				//关注时间
				if($v["subscribe_time"]>0){
					$subscribe_time = strtotime(date('Y-m-d'))+($v["subscribe_time"]*3600*24);
					$map['f.subscribe_time']=array("<=",$subscribe_time);
				}
				
				$map['m.uid']=array(">",0);

				if($v["paid"]>0 || $v["welth"]>0){
					$member = db('wechat_fans')->alias('f')->join(' cps_member_userapi u','u.wxmpid = f.openid','LEFT')->join(' cps_member m','m.uid = u.uid','LEFT')->where($map)->column('m.uid,f.openid,m.os');
				}else{
					$member = db('wechat_fans')->alias('f')->join(' cps_member_userapi u','u.wxmpid = f.openid','LEFT')->join(' cps_member m','m.uid = u.uid','LEFT')->where($map)->column('m.uid,f.openid,m.os');
				}
				//var_dump($member);exit();
				//开始推送
				if($member){
					foreach ($member as $vo){
						$openid = $vo["openid"];
						$is_push = db('customservice_log')->where(['msgid'=>$v['id'],'openid'=>$openid])->find();
						//$is_push = false;
						if(empty($is_push)){
							
							$param = json_decode($v["param"],true);	
							//var_dump($param);exit();
							if ($v["type"]==2){
								
								if($v["entry_type"]==1){//互动文本
									$content = $param["articles"][0]["title"];

									$pattern = "/(?:\{\[)(.*)(?:\]\()(.*)(?:\)\})/i";

									if($vo['os']=="android"){
										 
										$replacement = PHP_EOL.'<a href="weixin://kefumenu?kefumenucontent=${2}&kefumenuid=0">${1}</a>';
										$content = preg_replace($pattern,$replacement,$content);
									}elseif($vo['os']=="iphone"){
										$replacement = PHP_EOL.'<a href="weixin://bizmsgmenu?msgmenucontent=${2}&msgmenuid= ">${1}</a>';
										$content = preg_replace($pattern,$replacement,$content);
									}else{
										if(preg_match_all($pattern,$content, $matches,PREG_SET_ORDER)){
											foreach ($matches as $k=>$v){
												$articles  = '';
												$articles .= '<a href="weixin://kefumenu?kefumenucontent='.$v[2].'&kefumenuid=0">安卓手机点我：'.$v[1].'</a>'.PHP_EOL.PHP_EOL;
												$articles .= '<a href="weixin://bizmsgmenu?msgmenucontent='.$v[2].'&msgmenuid= ">苹果手机点我：'.$v[1].'</a>';
												$content = str_replace($v[0],$articles,$content);	
											}
										}
									}
								}else{
									$content = "";
									foreach ($param["articles"] as $item) {
										$content .= '<a href="'.$item["url"].'">'.$item["title"].'</a>'.PHP_EOL.PHP_EOL;
									}
								}
								
								$template = array(
									"touser"=>$openid,
									"msgtype"=>"text",
									"text"=>array('content'=>$content)
								);
								//var_dump($template);exit();
							}else{
								$template = array(
									"touser"=>$openid,
									"msgtype"=>"news",
									"news"=>$param
								);
							}

							if($v['wxmpid']){
								$auto = db('wxmp')->where('id',$v['wxmpid'])->field('appid,autoconfig,open_appid')->find();
								//公众号自动配置
								if($auto["autoconfig"]){
									$account = db('wxopen_account')->where('appid',$auto['open_appid'])->find();
									$wxComponentConfig = array(
										'component_appid'=>$account["appid"],
										'component_appsecret'=>$account["appsecret"],
										'encodingAesKey'=>$account["encodingKey"],
										'token'=>$account["token"]
									);
								}
							}
							
							if(array_key_exists("autoconfig",$auto)){
								$wxAuth = new WxComponentService($wxComponentConfig);
								$receive = $wxAuth->getWechat($auto['appid']);
							}else{
								$receive = &load_wechat($v['uid'],'Receive');
							}
							
							$res = $receive->sendCustomMessage($template);
							
							if($res && $res["errmsg"]=="ok"){
								db('customservice_log')->insert(['msgid'=>$v['id'],'openid'=>$openid,'create_at'=>time()]);
							}
						}
					}
				}
				db('customservice')->where("id=".$v['id'])->setField('completed', 1);
			}
		}
		
	}

	

	
	/**
      * send_customservice [发送客服消息函数]
      *
      * @param type $uid     [系统默认配置ID]
      * @param type $appid   [desc]
      * @param type $openid  [desc]
      * @param type $data    [消息数据 包含articles时msgtype可为空，否则msgtype为必填项]
      * @param type $msgtype [消息类型]
      *
      * @return type
    **/
	public function send_customservice($uid,$appid,$openid,$data,$msgtype=''){

		
		$auto = db('wxmp')->where('appid',$appid)->field('appid,autoconfig,open_appid')->cache(true)->find();
		//公众号自动配置
		if($auto["autoconfig"]){
			$account = db('wxopen_account')->where('appid',$auto['open_appid'])->cache(true)->find();
			$wxComponentConfig = array(
				'component_appid'=>$account["appid"],
				'component_appsecret'=>$account["appsecret"],
				'encodingAesKey'=>$account["encodingKey"],
				'token'=>$account["token"]
			);
		}
		if($auto["autoconfig"]){
			$wxAuth = new WxComponentService($wxComponentConfig);
			$receive = $wxAuth->getWechat($auto['appid']);
		}else{
			$receive = &load_wechat($uid,'Receive');
		}
		
		if (!empty($data["articles"])&&count($data["articles"]) > 1){
            $content = "";
			if($data["type"]==2){//文本
				foreach ($data["articles"] as &$item) {
					if(empty($item["url"])){
						$content .= $item["title"].PHP_EOL.PHP_EOL;
					}else{
						$content .= '<a href="'.$item["url"].'">'.$item["title"].'</a>'.PHP_EOL.PHP_EOL;
					}
				}
				$template = array(
					"touser"=>$openid,
					"msgtype"=>"text",
					"text"=>array('content'=>$content)
				);
			}else{//图文
				foreach ($data["articles"] as &$item) {
					$content .= emoji("\ue315").emoji("\ue231").'<a href="'.$item["url"].'">'.$item["title"].'</a>'.PHP_EOL.PHP_EOL;
				}

				$template = array(
					"touser"=>$openid,
					"msgtype"=>"text",
					"text"=>array('content'=>trim($content.emoji("\ue003")."为方便阅读请置顶公众号！".PHP_EOL."回复书名即可找到对应书籍！".emoji("\ue003")))
				);
			}			
        }else{
			if($msgtype=="text"){
				$template = array(
					"touser"=>$openid,
					"msgtype"=>"text",
					"text"=>array('content'=>$data)
				);
			}else{
				$template = array(
					"touser"=>$openid,
					"msgtype"=>"news",
					"news"=>$data
				);
			}
        }
		$result = $receive->sendCustomMessage($template);
		if($result["errmsg"]=="ok"){
			return true;
		}
		return false;
	}
	
	/*****同步用户头像 昵称 性别  城市 ******/
	public function pushavatar() {
		$result = [];
		$list = db('member_userapi')->alias('a')->join('__MEMBER__ m','m.uid = a.uid','left')->where('m.avatar is null')->field('a.uid,a.appid,a.wxmpid')->select();
		foreach($list as $v){
			$result[$v['uid']] = db('WechatFans')->where(['appid'=>$v['appid'],'openid'=>$v['wxmpid']])->field('headimgurl,nickname,sex,country,province,city')->find();
		}
		
		if(!empty($result)){
			//同步用户信息
			foreach(array_filter($result) as $k=>$v){
				$data['avatar'] = $v['headimgurl'];
				//$data['nickname'] = $v['nickname'];
				//$data['sex'] = $v['sex'];
				//$country = $v['country']?$v['country']:'';
				//$province = $v['province']?'-'.$v['province']:'';
				//$city = $v['city']?'-'.$v['city']:'';
				//$data['pos_city'] =$country.$province.$city;
				db('member')->where('uid',$k)->update($data);
			}
		}
		//echo "ok";
	}

	//同步微信公众号365天之内关注用户信息
	public function pushsubscribe() {
		$subscribe_time = strtotime(date('Y-m-d'))-(24*3600*7);
		//var_dump($subscribe_time);exit();
		$map['f.subscribe_time']=array(">=",$subscribe_time);
		$map['f.subscribe'] = 1;
		$member = db('wechat_fans')->alias('f')->join(' cps_member_userapi u','u.wxmpid = f.openid','LEFT')->join(' cps_member m','m.uid = u.uid','LEFT')->where($map)->column('u.uid');
		if($member){
			foreach ($member as $uid){
				if(!empty($uid)){
					Db::name('member')->where(['uid' =>$uid])->setField('is_attention', 1);
				}
			}
		}
	}


	/*****作者收入统计*****/
	public function writer_income() {
		$list = db('novel')->alias('n')->join('cps_member_writer w ','w.uid= n.authorid')->where('n.status=1 and n.authorid >0')->field('n.*,w.card_bank_name,w.card_number,w.realName')->select();
		$month = mktime(0,0,0,date('m'),1,date('Y'));
		$end_date = mktime(23,59,59,date('m'),date('t'),date('Y'));
		
		if($list){
			foreach ($list as $k=>$v){	
				$data = [];
				//本月收入是否已创建
				$income = db('writer_income')->where(['month'=>$month,'uid'=>$v['authorid'],'articleid'=>$v['id']])->find();
				//本月更新的章节字数
				$size = db('chapter')->where(['status' =>1,'articleid'=>$v['id'],'create_time'=>[['>=',$month],['<=',$end_date]]])->sum('size');

				$data['halfyearaward'] =0;//买断奖
				$data['basicliving'] =0;//保底奖
				$data['subscription'] =0;//订阅
				$data['bonus'] =0;//打赏
				
				if($v['signtype']==1){//买断签约
					$data['halfyearaward'] = $size/1000*$v['buyout'];
				}elseif($v['signtype']==2){
					//订阅计算
					$data['subscription'] = db('subscription')->where(['model'=>1,'articleid'=>$v['id'],'buytype'=>['in','2,4'],'create_time'=>[[">=",$month],["<=",$end_date]]])->sum('price');
			
					//打赏计算
					$data['bonus'] = db('bookbonus')->where(['model'=>1,'articleid'=>$v['id'],'create_time'=>[[">=",$month],["<=",$end_date]]])->sum('actvalue');					
				}else{

					//订阅计算
					$data['subscription'] = db('subscription')->where(['model'=>1,'articleid'=>$v['id'],'buytype'=>['in','2,4'],'create_time'=>[[">=",$month],["<=",$end_date]]])->sum('price');

					//计算方法： （书币*（1-推广成本）*分成比例）/100
					$data['subscription'] = ($data['subscription']*(1-($v['promotionCost']?$v['promotionCost']:config('promotioncost')))*($v['profitProportion']?$v['profitProportion']:config('authorincome')))/100;

					//打赏计算
					$data['bonus'] = db('bookbonus')->where(['model'=>1,'articleid'=>$v['id'],'create_time'=>[[">=",$month],["<=",$end_date]]])->sum('actvalue');	

					//计算方法：  （书币*（1-推广成本）*分成比例）/100
					$data['bonus'] = ($data['bonus']*(1-($v['promotionCost']?$v['promotionCost']:config('promotioncost')))*($v['profitProportion']?$v['profitProportion']:config('authorincome')))/100;

					$data['basicliving'] = $size/1000*$v['guaranteed'];
					//保底分成模式；保底大于分成  按保底算
					if($data['basicliving']>($data['subscription']+$data['bonus'])){
						$data['subscription'] =0;//订阅
						$data['bonus'] =0;//打赏
					}else{
						$data['basicliving'] = 0;
					}
				}
				
				if($income){
					$data['update_time'] =time();
					db('writer_income')->where('id='.$income['id'])->update($data);
				}else{
					$data['uid'] = $v['authorid'];
					$data['articleid'] = $v['id'];
					$data['articlename']=get_novel($v['id'],'title');
					$data['month'] = $month;
					$data['create_time'] = $data['update_time'] =time();
					db('writer_income')->insert($data);
				}
			} 
		}
	}

	//章节定时发布
	public function publishchapter() {
		$chapter = db('chapter')->where(["status"=>3,"publishtime"=>array(array(">",0),array("<=",time()))])->column('id,chaptername,size,articleid');
		//章节是否需要审核 1：直接发布  2：需要审核
		$status = config('writer_checkchapter')==1?2:1;
		
		if($chapter){
			foreach ($chapter as $k=>$v){
				db('chapter')->where("id=".$k)->update(['status' =>$status,'update_time'=>time()]);
				
				//更新小说总字数  总章节数
				$data = array(
					'update_time'=>time(),
					'lastvolumeid'=>$k,
					'lastvolume'=>$v['chaptername'],
					'chapters'=>array('exp', '`chapters`+1'),
					'size'=>array('exp','`size`+'.$v['size'])
				);
				db('novel')->where(array('id'=>$v['articleid']))->cache('bookinfo'.$v['articleid'])->update($data);
			}
		}

	}

	//超过30天章节自动清除
	public function recycle() {
		$result  = Db::query("select id from `cps_chapter` where now() > date_add(from_unixtime(create_time),interval -30 day) and `status` =4");
		
		if($result){
			foreach ($result as $k=>$v){
				Db::table('cps_chapter')->where('id',$v['id'])->delete();
			}
		}

	}
	/*****签约提醒*****/
	public function issign() {
		$author_issign = config('author_issign');
		$novel = db('novel')->where('size >='.$author_issign.' and status=1 and issign=0 and authorid>0 and fullflag=0')->column('id,title,authorid');
		if($novel){
			foreach ($novel as $k=>$v){
				$msgdata = array();
				$consult = db('consult')->where(['articleid'=>$v['id'],'type'=>1])->find();
				if(empty($consult)){
					$msgdata = array(
						"uid"=>1,
						"articleid"=>$v['id'],
						"status"=>2,
						"create_time"=>time(),
						"update_time"=>time(),
						"type"=>1,
						"receiveuser"=>$v['authorid'],
						"content"=>"你好，书籍《".$v['title']."》已达到签约条件。",
					);
					db('consult')->insert($msgdata);
				}
			}
		}
	}

	/*****VIP上架提醒*****/
	public function isvip() {
		$author_shelf = config('author_shelf');
		$novel = db('novel')->where('size >='.$author_shelf.' and status=1 and issign=1 and authorid>0 and fullflag=0 and isvip=0')->column('id,title,authorid');
		if($novel){
			foreach ($novel as $k=>$v){
				$msgdata = array();
				$consult = db('consult')->where(['articleid'=>$v['id'],'type'=>1,'isvip'=>1])->find();
				if(empty($consult)){
					$msgdata = array(
						"uid"=>1,
						"articleid"=>$v['id'],
						"status"=>2,
						"create_time"=>time(),
						"update_time"=>time(),
						"type"=>1,
						"isvip"=>1,
						"receiveuser"=>$v['authorid'],
						"content"=>"你好，书籍《".$v['title']."》已达到VIP上架条件。",
					);
					db('consult')->insert($msgdata);
				}
			}
		}
	}

	/******VIP会员次日结算 ********/
	public function vipstat() {
		//$sql = "select * from cps_order where type=2 and status=1";
		/*****获取充值配置******/
		$pay_setting = db('pay_setting')->where('type=2 and status=1')->select();
		//var_dump($pay_setting);exit();
		/**
		$total = count($pay_setting);
		if($pay_setting){
			$k = 0;
			foreach($pay_setting as $k=>$v) {
				if($k==0){
					$sql.= " and (money=".$v['price']." and update_time > ".(time() - $v['duration'] * 3600 * 24).")";
				}else{
					if($total==($k+1)){
						$sql.= " or (money=".$v['price']." and update_time > ".(time() - $v['duration']* 3600 * 24).")";
					}else{
						$sql.= " or (money=".$v['price']." and update_time > ".(time() - $v['duration']* 3600 * 24).")";
					}
				}
				$k++;
			}
		}else{
			exit();
		}
		**/
		//var_dump($sql);exit();
		//获取符合条件的数据
		//$list = Db::query($sql);
		$list = db('order')->where("type",2)->where("status",1)->group('uid')->order('update_time DESC')->field('uid,money')->select();
		
		if($list){
			foreach ($list as $key => $pay){
				$price = $day_egold = 0;
				foreach ($pay_setting as $k=>$v){
					if($v['price']==intval($pay['money'])){
						//金额除以总天数乘以100换算成每天需要的阅读币
						$day_egold = $pay['money']/$v['duration']*100;			
					}
				}
				//获取昨天VIP会员阅读书籍的总条数
				$total_subscription = db('subscription')->where("buytype=5 and uid=".$pay['uid']." and from_unixtime(create_time,'%Y-%m-%d')='".date("Y-m-d",strtotime("-1 day"))."'")->count();

				//有VIP会员阅读付费章节
				if($total_subscription>0){
					//VIP会员付费章节的 单章分配金额
					$price = round($day_egold /$total_subscription);

					//获得阅读VIP书籍
					$subscription = db('subscription')->where("buytype=5 and uid=".$pay['uid']." and from_unixtime(create_time,'%Y-%m-%d')='".date("Y-m-d",strtotime("-1 day"))."'")->group('articleid')->column('articleid,count(chapterid) as count');
					if($subscription){
						foreach ($subscription as $sk=>$sv){
							
							//书的包月金额
							$baoemoney = round($sv*$price);
							$writer_income = db('writer_income')->where('articleid='.$sk.' and month='.strtotime(date('Y-m',strtotime("-1 day"))))->field('id')->find();
							
							if($writer_income){
								db('writer_income')->where('id='.$writer_income['id'])->update(['sumvipegold' =>$baoemoney]);
							}else{
								if(get_novel($sk,'authorid')>0){
									$data = array(
										'status' =>0,
										'articleid' =>$sk,
										'articlename' =>get_novel($sk,'title'),
										'sumvipegold' =>$baoemoney,
										'uid' =>get_novel($sk,'authorid'),
										'create_time' =>time(),
										'update_time' =>time(),
										'month' =>strtotime(date('Y-m',strtotime("-1 day")))
									);
									db('writer_income')->insert($data);
								}
							}
							//日统计
							$report = model('Report');
							$report->actday(1,$sk,date("Y-m-d",strtotime("-1 day")),0,$baoemoney);
							//月统计
							$report->actmonth(1,$sk,date("Y-m",strtotime("-1 day")),0,$baoemoney);
							
						}
					}
				}
				
			}
		}
	}

	//充值赠币过期
	public function payexpire() {
		$payexpire = db('member')->where("zb > 0 and zb_expire >0 and zb_expire <=".strtotime(date('Y-m-d')))->field('uid,zb')->select();
		if($payexpire){
			foreach ($payexpire as $k=>$v){
				db('member')->where("uid=".$v['uid'])->update(['zb' => 0,'zb_expire'=>0]);
			}
		}
	}

	//签到赠币过期
	public function signexpire() {

		$signexpire = db('member_point')->where("expire_time <=".strtotime(date('Y-m-d')))->select();
		if($signexpire){
			foreach ($signexpire as $k=>$v){
				//db('member')->where("uid = ".$v["uid"])->setDec('sign_score',$v['egold']);
				db('member_point')->delete($v['id']);
			}
		}

		//处理可以用签到赠币总额
		$point = db('member_point')->where("expire_time >".strtotime(date('Y-m-d')))->group('uid')->field('sum(`egold`) as total ,uid')->select();
		if($point){
			foreach ($point as $k=>$v){
				db('member')->where("uid = ".$v["uid"])->setField('sign_score', $v['total']);
			}
		}
	}

	/**
	 * 随机获取数据
	 * @param string $num  抽取条数
	 * @param string $table    表名
	 * @param string $where    查询条件
	 * @return array 
	 */
	public function random_data($num,$table,$where=[],$field=null)
	{
		$pk = Db::name($table)->getPK();//获取主键
		
		$info = Db::name($table)->where($where)->field($pk)->select();//查询数据
		
		$n = '';
		$qu = '';
		foreach($info as $v=>$val){
			$n[$val[$pk]]= $val[$pk];
		}
		$data = array_rand($n,$num);
		if(is_array($data)){
			$qu = implode(',',$data);
			if($field){
				$list = Db::name($table)->where($pk,'in',$qu)->field($field)->select();
			}else{
				$list = Db::name($table)->where($pk,'in',$qu)->select();
			}
			
		}else{
			if($field){
				$list = Db::name($table)->where($pk,$data)->field($field)->select();
			}else{
				$list = Db::name($table)->where($pk,$data)->select();
			}
			
		}	
		
		return $list;
	}

	public function autoorder() {
		$spreadid= 0;
		$order = 'CZ_'.date("YmdHis").rand(1000, 9999);
		$articleid = array(0,1,2,3,4,5,6,7,8,9,10);
		$articleid = $articleid[array_rand($articleid,1)];

		$money = array(0,30,50,100,88,188,365);		
		$money = $money[array_rand($money,1)];
		
		if($money>0){

			$status = array(0,1);

			if($money==30||$money==50||$money==100){
				$type = 1;
			}else{
				$type = 2;
			}
			$paytype = 'wxpay';

			
			if($spreadid){
				$data['spreadid'] = $spreadid;
				$data['recharge_type'] = 2;
			}
			if($articleid){
				$data['articleid'] = $articleid;
			}
			$data['out_trade_no'] = $order;
			$data['paytype'] = $paytype;
			$data['money'] = $money;
			$data['type'] = $type;
			$data['create_time'] = time();
			$data['update_time'] = time();
			$data['status'] = $status[array_rand($status,1)];
			$data['uid'] = 1;
			db('order')->insert($data);
		}	
	}


	public function autouser() {

		$username = array("充血的你","独往归途","狂野男孩","刀伐戏子","野性傀儡","处处留情","穷极一生","稳步沙场","哑巴诉爱","夜半诗人","夏末浅念℃","何必再念@","蓦然訫殇","一相、情愿","盏茶浅抿","烟花易凉","╚橘色半夏╝","徦娤莣誋","逆游的鱼","紫若兰薇﹌","稚于初心","莫忘初心〆","梦醒时分°","樱花皇后","安之若素","暖于心ゆ","森蝶呦つ","北沐城歌","不屑゛去相信","仙女不成魔","天真-旳以为","不璃不弃","痛彻我心扉i","花开那年","庸俗措辭","乜许、就如许","尽撩少女心","涩gu 苏黎∫","忘不掉的伤","错蓝染笺","纤竹无泪、拒泪","感情错觉","我妈生我必有用/","睡在时光深处的温暖","唐尸三摆手i","何患无妻","被你伤到绝望！","永远的过客");
		$username = $username[array_rand($username,1)];
		$repassword = $password = generate_password(rand(6,10));
		$user = model('user');
		$email = "agentid";
		$result = $user->llq_rege($username, $password, $repassword, $email, false);
		var_dump($result);
	}
}